<template>
    <div class="user">
        <div class="user-dept">
            <yl-depts-tree v-model:value="selectedNodeKeys" :maxHeight="600" sreachAble></yl-depts-tree>
        </div>
        <div class="user-data">
            <div class="user-data__filter">
                <custom-filter
                    :selectOptions="selectOptions"
                    @onSubmit="handleInitQuery"
                    @onReset="handleResetQuery"
                ></custom-filter>
            </div>
            <div class="user-data__table">
                <yl-multi-button
                    class="multi-action"
                    :selectedRowKeys="selectedRowKeys"
                    @add="handleAddUser"
                    @multiDelete="handleMultiDelete"
                    @export="handleUserDownload"
                    :hideAdd="true"
                    :hideDelete="true"
                ></yl-multi-button>

                <a-table
                    :columns="columns"
                    :data-source="dataSource"
                    :row-key="setRowKey"
                    :pagination="pagination"
                    :loading="loading"
                    :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                    :scroll="{ x: 1080, y: 540 }"
                    @change="handleTableChange"
                >
                    <template v-for="item in columns" :key="item.dataIndex" v-slot:[item.slotName]>
                        <span>{{ t(`yl.${item.slotName}`) }}</span>
                    </template>
                    <template #enabled="{ record }">
                        <a-switch
                            v-model:checked="record.enabled"
                            @change="
                                (val) => {
                                    changeSwitch(val, record);
                                }
                            "
                        />
                    </template>
                    <template #customAction="{ record }">
                        <a-button class="action-btn" @click="handleEditUser(record)" type="primary" size="small">
                            <template #icon>
                                <EditOutlined />
                            </template>
                        </a-button>
                        <a-popconfirm placement="topRight" @confirm="handleDelete(record.id)">
                            <template #title>
                                <p>{{ t('yl.deleteConfirmtext') }}</p>
                            </template>
                            <a-button class="action-btn" type="danger" size="small">
                                <template #icon>
                                    <Delete />
                                </template>
                            </a-button>
                        </a-popconfirm>
                    </template>
                </a-table>
            </div>
        </div>
        <yl-user-model
            :visible="visible"
            :loading="confirmLoading"
            :title="modalTitle"
            :user="selectedRow"
            @cancle="handleCancle"
            @submit="handleSubmit"
        ></yl-user-model>
    </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, computed, onUnmounted, reactive, toRefs, watch, createVNode } from 'vue';
import ylDeptsTree from '@/components/ylDeptsTree.vue';
import ylMultiButton from '@/components/ylMultiButton.vue';
import ylUserModel from './components/userModel.vue';
import customFilter from './components/tableFilter.vue';
import { useI18n } from 'vue-i18n';
import columns from './userColumns';
import useTables from './userTable';
import { addUser, editUser, UserDownload } from '@/api/user/index';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { deleteEmptyKey } from '@/utils/help';
import useDeleteUser from './deleteUser';
import { PaginationQuery } from '@/types/table';
import { message, Modal } from 'ant-design-vue';

interface State {
    modalTitle: string;
    confirmLoading: boolean;
    selectedNodeKeys: (string | number)[];
}

export default defineComponent({
    name: 'user',
    components: {
        ylDeptsTree,
        ylMultiButton,
        ylUserModel,
        customFilter,
    },

    setup() {
        const { t } = useI18n();
        let { selectedRow, getUsersData, tableQuery, visible } = useTables;

        const state: State = reactive({
            modalTitle: computed(() => (selectedRow.value.id ? t('yl.editUser') : t('yl.addUser'))),
            confirmLoading: false,
            selectedNodeKeys: [],
            tableScrollHeight: 540,
        });
        onMounted(async () => {
            getUsersData(tableQuery);
        });
        console.log(state.selectedNodeKeys);
        // 设置table row key
        const setRowKey = (record: { [x: string]: any }) => record.id;

        // 初始化搜索
        const handleInitQuery = (query: PaginationQuery | TableCustomFilter) => {
            tableQuery.page = 0;
            const params = Object.assign({}, tableQuery, query);
            getUsersData(params);
        };
        // 重置搜索条件
        const handleResetQuery = () => {
            delete tableQuery.deptId;
            handleInitQuery(tableQuery);
        };

        // 选择项发生改变
        const changeSwitch = (keys: any, row: any) => {
            Modal.confirm({
                title: t('yl.tip'),
                icon: createVNode(ExclamationCircleOutlined),
                content: t('yl.changeDeptStatusConfirm', { status: keys ? t('yl.enable') : t('yl.disable'), name: row.username }),
                onOk() {
                    const data: { [x: string]: any } = {
                        email: row.email,
                        enabled: keys,
                        gender: row.gender,
                        id: row.id,
                        nickName: row.nickName,
                        phone: row.phone,
                        roleIds: row.roles.map((item: any) => {
                            return item.id;
                        }),
                        username: row.username,
                    };

                    if (row.dept && row.dept.id) {
                        data.dept = { id: row.dept.id };
                    }
                    editUser(data)
                        .then(() => {
                            const timer = setTimeout(() => {
                                handleInitQuery(tableQuery);
                                clearTimeout(timer);
                            }, 500);
                        })
                        .catch(() => {});
                },
                onCancel() {
                    row.enabled = !keys;
                },
            });

            // 多余的操作 接口数据类型问题
        };
        // 隐藏弹窗
        const handleCancle = () => {
            visible.value = false;
        };
        // 提交添加/编辑用户
        const handleSubmit = (user: NormalObj) => {
            // 刪除空字段
            deleteEmptyKey(user);
            state.confirmLoading = true;
            const msg = user.id ? t('yl.editSuccess') : t('yl.addSuccess');
            const realRequest = user.id ? editUser(user) : addUser(user);
            realRequest
                .then(() => {
                    state.confirmLoading = false;
                    message.success(msg);
                    visible.value = false;
                    const timer = setTimeout(() => {
                        handleInitQuery(tableQuery);
                        clearTimeout(timer);
                    }, 500);
                })
                .catch(() => {
                    state.confirmLoading = false;
                });
        };

        // 导出用户数据
        const handleUserDownload = () => {
            let name = t('yl.userMgt');
            UserDownload(name);
        };

        // 选择公司节点 初始化table
        watch(
            () => state.selectedNodeKeys,
            (node) => {
                tableQuery.deptId = node[0];
                handleInitQuery(tableQuery);
            }
        );

        // 筛选状态列表
        const selectOptions = [
            {
                label: t('yl.active'),
                value: 'true',
            },
            {
                label: t('yl.disabled'),
                value: 'false',
            },
        ];
        return {
            columns,
            selectOptions,
            ...toRefs(state),
            setRowKey,
            t,
            handleSubmit,
            ...useTables,
            handleCancle,
            ...useDeleteUser(),
            handleInitQuery,
            handleResetQuery,
            changeSwitch,
            handleUserDownload,
            deleteEmptyKey,
        };
    },
});
</script>

<style lang="scss" scoped>
.user {
    @include flex;
    width: 100%;
    &-dept {
        flex-basis: 200px;
        min-width: 200px;
    }
    &-data {
        flex: 1;
        padding-left: $width20;
        &__filter {
            @include flex;
        }
        &__table {
            padding: $width20 $width0;
            .multi-action {
                background: $white;
            }
        }
    }
}
</style>
